import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

shama_event_project_api = Blueprint('shama_event_project_api', __name__)
shama_event_project_down_api = Blueprint('shama_event_project_down_api', __name__)
shama_event_project_sync_api = Blueprint('shama_event_project_sync_api', __name__)


@shama_event_project_api.route('/shama_event_project', methods=['POST'])
def shama_event_project():
    params = json.loads(request.data)

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if _action == 'detail':
        query = ShamaEventProject.query.filter_by(project=_project).first()
        basic = json.loads(query.basic)
        if '_tag' not in basic:
            basic['_tag'] = []

        reward = json.loads(query.reward)
        # for node in reward:
        #     if 'game_difficult' not in node:
        #         node['game_difficult'] = 1
        #     if 'castle_lv' not in node:
        #         node['castle_lv'] = 8

        tmp = {
            "project": int(query.project),
            'basic': basic,
            'reward': reward
        }
        result_data['data']['item'] = tmp

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        if _part == 'basic':
            ShamaEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'reward':
            ShamaEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(_data)
            })

        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    
    elif _action == 'calendar_doc_id_list':
        return json.dumps(GetNewOperationEventList('ghost_town_event', 'title'))

    elif _action == 'game_difficult_list':
        building_content = loadGame()['game_shama_building']
        tower_content = loadGame()['game_shama_tower']
        result = []
        for v in building_content.values():
            tmp = {
                'value': v['a'][0],
                'label': str(v['a'][0])
            }
            if tmp not in result:
                result.append(tmp)
        for v in tower_content.values():
            tmp = {
                'value': v['a'][0],
                'label': str(v['a'][0])
            }
            if tmp not in result:
                result.append(tmp)

        return json.dumps(result)

    return jsonify(result_data)


@shama_event_project_down_api.route('/shama_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def shama_event_project_down(is_push):
    shama_event_project = {}

    query = ShamaEventProject.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        reward = json.loads(q.reward)

        _reward = {}
        for i in reward:
            _reward[str(i['difficulty'])] = {
                'reward_list': RewardToTMysqlNew(i['reward'])
            }
        for i in range(0, 5):
            if str(i) not in _reward:
                _reward[str(i)] = {
                    'reward_list': []
                }

        _tag = basic['_tag'] if '_tag' in basic else []

        # difficult = []
        # for dif_node in reward:
        #     if 'game_difficult' in dif_node:
        #         game_difficult = dif_node['game_difficult']
        #     else:
        #         game_difficult = 1
        #     if 'castle_lv' in dif_node:
        #         castle_lv = dif_node['castle_lv']
        #     else:
        #         castle_lv = 8
        #     difficult.append({
        #         'game_difficult': game_difficult,
        #         'castle_lv': castle_lv
        #         })

        shama_event_project[str(project)] = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 18,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': RewardToTMysqlNew(basic['calendar_reward']),
                'show_type': 0
            },
            'basic': {
                'event_ui': basic['event_ui']
            },
            'localization': json.loads(q.localization),
            'reward': _reward
        }
    if is_push == 0:
        response = DownLoad('shama_event_project', shama_event_project, 0)
    if is_push == 1:
        current_data = read_s3_file('shama_event_conf')
        # for i in shama_event_project:
        #     current_data['proj'][i] = shama_event_project[i]
        current_data['proj'] = shama_event_project

        r1 = DownLoad('shama_event_conf', current_data, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response


@shama_event_project_sync_api.route('/shama_event_project_sync', methods=['GET', 'POST'])
def shama_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], reward_list)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/shama_event_conf_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data['proj']))
    _currentIndex = 0
    for i in data['proj']:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data['proj'])))
        _project = int(i)
        _basic = data['proj'][i]['basic']
        _localization = data['proj'][i]['localization']
        _remark = str(_project)
        if "1" in _localization:
            if "title" in _localization["1"]:
                _remark = _localization["1"]["title"]

        _basic['calendar_doc_id'] = data['proj'][i]['calendar_conf']['localization']['title']

        _basic['calendar_reward'] = RewardShowToDocBonus3(data['proj'][i]['calendar_conf']['reward'], reward_list)

        _reward = []
        for j in range(0, 5):
            if str(j) not in data['proj'][i]['reward']:
                _reward.append({
                    'difficulty': int(j),
                    'reward': []
                })
            else:
                _reward.append({
                    'difficulty': int(j),
                    'reward': RewardShowToDocBonus3(data['proj'][i]['reward'][str(j)]['reward_list'], reward_list)
                })


        new_project_data = ShamaEventProject(
            project=_project,
            basic=json.dumps(_basic),
            localization=json.dumps(_localization),
            reward=json.dumps(_reward),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})
